<?php
namespace wechat;

class Material extends Base
{

    /**
     * 获取临时素材  2017-03-11
     */
    public function getmedia($mediaid, $access_token)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=$access_token&media_id=$mediaid";

        $img = file_get_contents($url);
        //$result = $this -> httpdata($url);
        return $img;
    }

    /**
     * 上传临时素材  2017-10-15
     * 文件路径需为绝对路径
     */
    public function upload($media, $access_token, $type, $attach = array())
    {
        $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=$type";
        $data['media'] = "@".realpath($media);
        //$data['media'] = new \CURLFile($media);
        $result = $this->httpdatas($url, $data);
        !isset($attach['uid']) && $attach['uid'] = 0;
        apilog($attach['uid'], 'wechat', 'mediaupload', $url, $data, $result);

        return $result;
    }

    /**
     * 上传临时素材POST请求  2017-10-15
     */
    public function httpdatas($url, $data)
    {
        $ch = curl_init();
        //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $status = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($status, true);
        return $res;
    }

}